define(function(require, exports, module) {

  var Backbone = require('backbone');
  var $ = require('jquery');
  var _ = require('underscore');
  var jsonview = require('jsonview');
  var tmpl = require('text!../tmpl.html');

  function main() {
    var $app = $('<div id="app">');
    $('#main').html($app);

    $app.append(tmpl);

    var isDrag = false;
    var c=document.getElementById("myCanvas");
    var cxt=c.getContext("2d");
    var recX_start = 600;
    var recX_len = 100;
    var recY_start = 0;
    var recY_len = 200;

    // suppose start is closer to the origin
    var start = [160, 300];
    var end = [recX_start+recX_len, recY_start + recY_len/2];

    draw();

    var lastX, lastY;

    addEventListener('mousedown', function(e){
      isDrag = true;
      lastX = e.x;
      lastY = e.y;
    })

    addEventListener('mousemove', function(e){
      if(isDrag){
        recX_start -= lastX - e.x;
        recY_start -= lastY - e.y;
        lastX = e.x;
        lastY = e.y; 
      }
    })

    addEventListener('mouseup', function(){
      isDrag = false;
    })

    function draw(){
      requestAnimationFrame(draw);
      cxt.clearRect(0,0,1000,800);

      end = [recX_start+recX_len, recY_start + recY_len/2];
      cxt.fillStyle="#FF0000";
      cxt.fillRect(recX_start,recY_start,recX_len,recY_len);

      cxt.beginPath();
      cxt.moveTo(start[0] - 10, start[1]); 
      cxt.lineTo(start[0], start[1]); 
 
      
      if( start[1] > recY_start + recY_len ||  start[1] < recY_start ){
        cxt.lineTo( end[0] + 100, start[1]);
      } 
      else{ 
        cxt.lineTo( start[0], recY_start + recY_len + 30);
        cxt.lineTo( end[0] + 100, recY_start + recY_len + 30); 
      }

      cxt.lineTo(end[0] + 100, end[1]);
      cxt.lineTo(end[0], end[1]);
      cxt.stroke();

    }
  }

  return main;
})
